"ui";
var 配置 = storages.create("zhubzs");
//App配置信息
var App = {
    name: "抖商主播助手",
    version: "1.8",
    package: "com.douszbzs.android",
    dy_package: "com.ss.android.ugc.aweme",
    dy_version: "17.7"
}


ui.layout(
    <ScrollView>
        <vertical>
            <appbar>
                <toolbar id="bt" title={App.name} />
            </appbar>
            <Switch id="autoService" text="无障碍服务" checked="{{auto.service != null}}" padding="8 8 8 8" textSize="15sp" />
            <horizontal>
                <text text="  关键词1：" gravity="left" />
                <input id="key1" hint="填写关键词                    " textSize="15sp" gravity="center" />
            </horizontal>
            <horizontal>
                <text text="  回复内容：" gravity="left" />
                <input id="volue1" hint="符合关键词后回复的内容" textSize="15sp" gravity="center" />
            </horizontal>
            <horizontal>
                <text text="  关键词2：" gravity="left" />
                <input id="key2" hint="填写关键词                    " textSize="15sp" gravity="center" />
            </horizontal>
            <horizontal>
                <text text="  回复内容：" gravity="left" />
                <input id="volue2" hint="符合关键词后回复的内容" textSize="15sp" gravity="center" />
            </horizontal>
            <text text="   温馨提示：" gravity="left" />
            <text text="   1.匹配方式采用模糊匹配；" gravity="left" />
            <text text="   2.打开直播间后启动软件即可；" gravity="left" />
            <text text="   3.关键词和回复内容必须填写；" gravity="left" />
            <horizontal>
                <text text="   系统提示：" gravity="left" />
                <checkbox id="支持" text="本软件无需root权限。" checked="true" />
            </horizontal>


     
            <button id="start" text="开始运行" style="Widget.AppCompat.Button.Colored" />
          

            <horizontal>
                <text id="ver" text="   当前软件版本：  " gravity="left" />
                <text id="安卓版本" textSize="15sp" />
            </horizontal>
        </vertical>
    </ScrollView>
);
ui.安卓版本.text("   本机安卓版本：" + device.release + "");



ui.autoService.on("check", function (checked) {
    if (checked && auto.service == null) {
        app.startActivity({
            action: "android.settings.ACCESSIBILITY_SETTINGS"
        });
    }
    if (!checked && auto.service != null) {
        auto.service.disableSelf();
    }
});




var 悬块 = function (window, view) {
    if (!window || !view) {
        throw "缺参数";
    };
    this.x = 0, this.y = 0;
    this.windowX, this.windowY;
    this.downTime = 500;
    this.Timeout = 0;
    this.Click = function () { };
    this.LongClick = function () { };
    this.setClick = function (fun) {
        //判断参数类型是否为函数？
        if (typeof fun == "function") {
            this.Click = fun;
        };
    };
    this.setLongClick = function (fun, ji) {
        //判断参数类型是否为函数？
        if (typeof fun == "function") {
            this.LongClick = fun;
            //判断参数是否可为设置数字？
            if (parseInt(ji) <= 1000) {
                this.downTime = parseInt(ji);
            };
        };
    };

    view.setOnTouchListener(new android.view.View.OnTouchListener((view, event) => {
        switch (event.getAction()) {
            //按下事件。
            case event.ACTION_DOWN:
                //按下记录各种坐标数据。
                this.x = event.getRawX();
                this.y = event.getRawY();
                this.windowX = window.getX();
                this.windowY = window.getY();
                //创建一个定时器用来定时执行长按操作。
                this.Timeout = setTimeout(() => {
                    this.LongClick();
                    this.Timeout = 0;
                }, this.downTime);
                return true;
            //移动事件。
            case event.ACTION_MOVE:
                //移动距离过大则判断为移动状态
                // if (Math.abs(event.getRawY() - this.y) > 5 && Math.abs(event.getRawX() - this.x) > 5) {
                //     //移动状态清除定时器
                //     if (this.Timeout) {
                //         //定时器存在则清除定时器。
                //         clearTimeout(this.Timeout);
                //         this.Timeout = 0;
                //     };
                //     //移动手指时调整悬浮窗位置
                //     window.setPosition(this.windowX + (event.getRawX() - this.x), this.windowY + (event.getRawY() - this.y));
                // };
                return true;
            //抬起事件。
            case event.ACTION_UP:
                if (this.Timeout) {
                    clearTimeout(this.Timeout);
                    this.Timeout = 0;
                    this.Click();
                };
                return true;
        };
        return true;
    }));
};
var activeSubjectsArr = [];//初始化后的包含json格式的数组
var startime = Date.parse(new Date());

readconfig();//读取配置

ui.start.on("click", function () {
    //程序开始运行之前判断无障碍服务
    if (auto.service == null) {
        toast("请先开启无障碍服务！");
        return;
    }
    saveconfig();//保存配置
    xf();//悬浮窗
    抖音();//主线程
});

function 初始化关键词() {
    var activeSubjectsName = [];//关键词数组
    activeSubjectsName.push(ui.key1.text())
    activeSubjectsName.push(ui.key2.text())
    var activeSubjectsNum = [];//回复内容数组
    activeSubjectsNum.push(ui.volue1.text())
    activeSubjectsNum.push(ui.volue2.text())

    for (var i = 0; i < activeSubjectsName.length; i++) {
        // console.log(i);
        var activeSubjectsObject = {};
        for (var j = 0; j < activeSubjectsNum.length; j++) {
            if (i == j) {
                activeSubjectsObject.name = activeSubjectsName[i];
                activeSubjectsObject.value = activeSubjectsNum[j];
                activeSubjectsArr.push(activeSubjectsObject);
            }
        }
    }
    if (activeSubjectsArr.length > 0) {
        log("初始化关键词成功");
    } else {
        log("初始化关键词失败");
        exit();
    }
}
function 关键词回复() {
    var jihe = [];
    while (true) {
        sleep(200);
        if (textMatches("小时榜|小时榜.*|说点什么.*|.*本场点赞").exists()) {
            var uc = textMatches(".+：.+").visibleToUser().find();
            for (i = 0; i < uc.length; i++) {
                var result = false;
                var a = 取文本右边(uc[i].text(), "：")
                str1 = a;
                for (let k = 0; k < jihe.length; k++) {
                    if (jihe[k] == str1) {
                        result = true;
                        break;  //判断如果重复就跳出
                    }
                }

                if (result == false) {
                    jihe.push(str1);//加入数组
                    log("读取发言：" + str1)
                    for (let m = 0; m < activeSubjectsArr.length; m++) {
                        if (str1.indexOf(activeSubjectsArr[m].name) >= 0) {
                            log("关键词符合：" + activeSubjectsArr[m].name);
                            log("执行回复：" + activeSubjectsArr[m].value)
                            发言(activeSubjectsArr[m].value)
                            break;
                        }
                    }
                }
                if (jihe.length >= 10) {
                    //为了防止同一个人后面发送的相同内容无法记录，这里自动清除数组中第一个元素
                    jihe.shift();
                }
            }
        } else {
            var a = desc("发送").className("android.widget.Button").visibleToUser().findOne(1000);
            if (a) {
                a.click();
                sleep(random(500, 1000));
            }
            var uc = className("android.widget.EditText").visibleToUser().find();
            if (uc.length > 0) {
                back();
                sleep(2000);
            }
            if (text("立即赠送").visibleToUser().exists()) {
                sleep(random(500, 1000));
                back();
            }
            log("未检测到直播间窗口");
            sleep(10000);
        }
    }
}
function 抖音() {
    主线程 = threads.start(function () {
        console.setTitle("关键词");
        console.show();
        ts("执行操作：脚本开始运行");
        app.launchPackage("com.ss.android.ugc.aweme");
        初始化关键词();
        sleep(5000);
        关键词回复();
    })
}
function xf() {
    var thread = threads.start(function op() {
        var window = floaty.window(
            // <button id="but" w="35" h="60" text="停止" />
            <button id="but" text="stop" />
            // <img id="but" src="file://stop1.png" />
        );
        window.setPosition(10, device.height / 3)
        setInterval(() => { }, 500);
        var ad = new 悬块(window, window.but);
        ad.setLongClick(function () {
            var yxtime = (Date.parse(new Date()) - startime) / 1000;
            yxtime = formatSeconds(yxtime);
            log("提示：用户停止运行");
            log("时间提示：运行" + yxtime);

            exit();
        });
        ad.setClick(function () {
            var yxtime = (Date.parse(new Date()) - startime) / 1000;
            yxtime = formatSeconds(yxtime);
            log("提示：用户停止运行");
            log("时间提示：运行" + yxtime);

            exit();
        })
    })
    //创建一个新的悬浮控制模块 ad 并带入参数(所要控制的悬浮窗和用来控制悬浮窗移动的控件)。

}
function saveconfig() {
    配置.put("key1", ui.key1.text());
    配置.put("key2", ui.key2.text());
    配置.put("volue1", ui.volue1.text());
    配置.put("volue2", ui.volue2.text());
    配置.put("支持", ui.支持.checked);
}
function readconfig() {
    ui.key1.text(配置.get("key1", "包邮吗"));
    ui.key2.text(配置.get("key2", ""));
    ui.volue1.text(配置.get("volue1", "本直播间全场包邮，请放心下单。"));
    ui.volue2.text(配置.get("volue2", ""));
    ui.支持.checked = Boolean(配置.get("支持", true));
}
//检测更新

function ts(text) {
    log(text)
}
function formatSeconds(value) {
    var secondTime = parseInt(value);// 秒
    var minuteTime = 0;// 分
    var hourTime = 0;// 小时
    if (secondTime > 60) {
        minuteTime = parseInt(secondTime / 60);
        secondTime = parseInt(secondTime % 60);
        if (minuteTime > 60) {
            hourTime = parseInt(minuteTime / 60);
            minuteTime = parseInt(minuteTime % 60);
        }
    }
    var result = "" + parseInt(secondTime) + "秒";

    if (minuteTime > 0) {
        result = "" + parseInt(minuteTime) + "分" + result;
    }
    if (hourTime > 0) {
        result = "" + parseInt(hourTime) + "小时" + result;
    }
    return result;
}
function 发言(str) {
    var uc = textMatches("说点.+").visibleToUser().findOne(1000);
    if (uc) {
        // uc.click();
        click(uc.text());
        sleep(random(500, 3000));
    } else {
        log("重要提示：未找到输入框，多次提示，请手动退出直播间重新进");
        sleep(1000);
    }
    inputtxt(str);
    sleep(random(500, 1000));
    var a = desc("发送").className("android.widget.Button").visibleToUser().findOne(1000);
    if (a) {
        a.click();
        sleep(random(500, 1000));
        ts("休息时间：3秒");
        sleep(3 * 1000);
    } else {
        var a = text(str).visibleToUser().findOne(1000);
        if (a) {
            click(device.width - 10, a.bounds().centerY());
            sleep(random(500, 1000));
            ts("发送内容：" + str);
            ts("休息时间：3秒");
            sleep(3 * 1000);
        }
    }
}
function inputtxt(str) {
    var i = 0;
    while (true) {
        setText(str.substr(0, i));
        sleep(random(20, 100));
        i = i + 1;
        if (i > str.length) {
            break;
        }
    }

}
function 取文本右边(str, a)  //取文本的中间值
{
    var w1 = str.indexOf(a);
    if (w1 < 0) {
        return false;
    };
    w1 = w1 + a.length;
    w2 = str.length;
    return str.substr(w1, w2 - w1);
}
